package Dinner;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.storage.Fooddatabase;
import com.example.storage.R;

import java.util.List;
import java.util.Locale;

import mealhistory.Mealitem;

public class DinnerAdapter extends RecyclerView.Adapter<DinnerAdapter.ViewHolder>{
    private List<Mealitem> dinnerList;
    private Context context;
    private Fooddatabase foodhelper;

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView foodName, foodWeight, calories;
        ImageView foodImage;

        public ViewHolder(View itemView) {
            super(itemView);
            foodName = itemView.findViewById(R.id.textFoodName);
            foodWeight = itemView.findViewById(R.id.textFoodWeight);
            calories = itemView.findViewById(R.id.textCalories);
            foodImage = itemView.findViewById(R.id.imageFood);
        }
    }

    public DinnerAdapter(Context context, List<Mealitem> dinnerList) {
        this.context = context;
        this.dinnerList = dinnerList;
        foodhelper = new Fooddatabase(context, "FOODSTORE.db", null, 3);
    }

    @NonNull
    @Override
    public DinnerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_dinner_item, parent, false);
        return new DinnerAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DinnerAdapter.ViewHolder holder, int position) {
        Mealitem item = dinnerList.get(position);
        holder.foodName.setText(item.getFoodname());
        holder.foodWeight.setText(String.format(Locale.getDefault(), "%d g", item.getWeight()));
        holder.calories.setText(String.format(Locale.getDefault(), "%.2f kcal", item.getConsumption()));
        // 使用 Glide 加载图片
        String foodName = item.getFoodname();
        String imageUrl = foodhelper.getImageUrlByFoodName(foodName);
        if (imageUrl != null && !imageUrl.isEmpty()) {
            Glide.with(context)
                    .load(imageUrl)
                    .placeholder(R.drawable.ic_img_not_found)
                    .error(R.drawable.ic_img_not_found)
                    .into(holder.foodImage);
        } else {
            holder.foodImage.setImageResource(R.drawable.ic_img_not_found); // 如果 URL 为空，显示默认图片
        }
    }

    @Override
    public int getItemCount() {
        return dinnerList.size();
    }

}
